<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度地图导航路线服务</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .control-panel {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }
        .input-group {
            flex: 1;
            min-width: 300px;
            position: relative;
        }
        .input-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .input-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .button {
            background-color: #4285f4;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
        }
        .button:hover {
            background-color: #3367d6;
        }
        #status {
            color: red;
            margin: 10px 0;
        }
        
        /* 路线表格样式 */
        .routes-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .routes-table th, .routes-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }
        .routes-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .routes-table tr:hover {
            background-color: #f5f5f5;
            cursor: pointer;
        }
        .routes-table tr.selected {
            background-color: #e3f2fd;
        }
        .tag {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
            background-color: #4285f4;
        }
        .tag.recommended {
            background-color: #34a853;
        }
        .tag.alternative1 {
            background-color: #fbbc05;
        }
        .tag.alternative2 {
            background-color: #ea4335;
        }
        
        /* 路线详情样式 */
        .route-details {
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
        }
        .route-details h3 {
            margin-top: 0;
        }
        .step {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .step:last-child {
            border-bottom: none;
        }
        .steps-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .steps-table th, .steps-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .steps-table th {
            background-color: #f9f9f9;
        }
        
        /* 搜索结果下拉菜单 */
        .search-results {
            position: absolute;
            width: 100%;
            max-height: 300px;
            overflow-y: auto;
            background-color: white;
            border: 1px solid #ddd;
            border-top: none;
            z-index: 1000;
            display: none;
        }
        .search-results .result-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .search-results .result-item:hover {
            background-color: #f5f5f5;
        }
        .search-results .result-item .name {
            font-weight: bold;
        }
        .search-results .result-item .address {
            font-size: 12px;
            color: #666;
        }
        .search-results .result-item .coords {
            font-size: 12px;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>百度地图导航路线服务</h1>
        
        <div class="control-panel">
            <div class="input-group">
                <label for="origin-search">起点</label>
                <input type="text" id="origin-search" placeholder="输入地点名称，如：天宫">
                <div id="origin-search-results" class="search-results"></div>
                <input type="hidden" id="origin-input" value="39.911354,116.229613">
                <div id="origin-coords" style="font-size: 12px; color: #666; margin-top: 5px;">纬度: 39.911354, 经度: 116.229613</div>
            </div>
            <div class="input-group">
                <label for="destination-search">终点</label>
                <input type="text" id="destination-search" placeholder="输入地点名称，如：天宫">
                <div id="destination-search-results" class="search-results"></div>
                <input type="hidden" id="destination-input" value="39.890894,116.481957">
                <div id="destination-coords" style="font-size: 12px; color: #666; margin-top: 5px;">纬度: 39.890894, 经度: 116.481957</div>
            </div>
            <div>
                <label>&nbsp;</label>
                <button id="search-btn" class="button">查询路线</button>
            </div>
        </div>
        
        <div id="status"></div>
        
        <!-- 路线表格 -->
        <h2>路线列表</h2>
        <table id="routes-table" class="routes-table" style="display: none;">
            <thead>
                <tr>
                    <th>路线标签</th>
                    <th>距离(公里)</th>
                    <th>耗时</th>
                    <th>红绿灯数量</th>
                    <th>路况</th>
                    <th>过路费</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="routes-tbody">
                <!-- 路线数据将通过JavaScript动态添加 -->
            </tbody>
        </table>
        
        <!-- 路线详情 -->
        <div id="route-details" class="route-details" style="display: none;">
            <h2>路线详情</h2>
            <div id="route-summary"></div>
            <h3>行驶步骤</h3>
            <table class="steps-table" id="steps-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>道路名称</th>
                        <th>指示</th>
                        <th>距离</th>
                        <th>耗时</th>
                        <th>路况</th>
                    </tr>
                </thead>
                <tbody id="steps-tbody">
                    <!-- 步骤数据将通过JavaScript动态添加 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 引入百度地图API用于地点搜索 -->
    <script th:inline="javascript">
        // 获取API密钥
        var apiKey = /*[[${apiKey}]]*/ '您的百度地图API密钥';
    </script>
    <script>
        // 全局变量
        var routeResults = [];
        var currentRouteIndex = -1;
        
        // 页面加载完成后初始化
        window.onload = function() {
            // 加载百度地图API
            loadBaiduMapsAPI();
            
            // 绑定按钮事件
            document.getElementById('search-btn').onclick = searchRoute;
            
            // 绑定搜索框事件
            document.getElementById('origin-search').addEventListener('input', function() {
                searchPlace(this.value, 'origin');
            });
            
            document.getElementById('destination-search').addEventListener('input', function() {
                searchPlace(this.value, 'destination');
            });
            
            // 设置默认值
            document.getElementById('status').innerHTML = "请输入起点和终点，然后点击查询按钮";
        };
        
        // 加载百度地图API
        function loadBaiduMapsAPI() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://api.map.baidu.com/api?v=3.0&ak=' + apiKey + '&callback=initBaiduMaps';
            document.body.appendChild(script);
        }
        
        // 初始化百度地图
        function initBaiduMaps() {
            console.log('百度地图API加载完成');
        }
        
        // 搜索地点
        function searchPlace(keyword, type) {
            if (!keyword || keyword.length < 2) {
                document.getElementById(type + '-search-results').style.display = 'none';
                return;
            }
            
            // 使用后端API搜索地点
            fetch(`/api/navigation/place/search?keyword=${encodeURIComponent(keyword)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 0 && data.results && data.results.length > 0) {
                        displaySearchResults(data.results, type);
                    } else {
                        document.getElementById(type + '-search-results').innerHTML = '<div class="result-item">未找到相关地点</div>';
                        document.getElementById(type + '-search-results').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('搜索地点出错:', error);
                    document.getElementById(type + '-search-results').innerHTML = '<div class="result-item">搜索出错</div>';
                    document.getElementById(type + '-search-results').style.display = 'block';
                });
        }
        
        // 显示搜索结果
        function displaySearchResults(results, type) {
            var resultsDiv = document.getElementById(type + '-search-results');
            resultsDiv.innerHTML = '';
            
            for (var i = 0; i < Math.min(results.length, 10); i++) {
                var place = results[i];
                var item = document.createElement('div');
                item.className = 'result-item';
                item.innerHTML = `
                    <div class="name">${place.name}</div>
                    <div class="address">${place.address || '未知地址'}</div>
                    <div class="coords">纬度: ${place.location.lat}, 经度: ${place.location.lng}</div>
                `;
                
                // 点击结果项时设置坐标
                item.addEventListener('click', (function(place) {
                    return function() {
                        setCoordinates(type, place.location.lat, place.location.lng, place.name);
                        resultsDiv.style.display = 'none';
                    };
                })(place));
                
                resultsDiv.appendChild(item);
            }
            
            resultsDiv.style.display = 'block';
        }
        
        // 设置坐标
        function setCoordinates(type, lat, lng, name) {
            document.getElementById(type + '-search').value = name;
            document.getElementById(type + '-input').value = lat + ',' + lng;
            document.getElementById(type + '-coords').innerHTML = '纬度: ' + lat + ', 经度: ' + lng;
        }
        
        // 搜索路线
        function searchRoute() {
            var origin = document.getElementById('origin-input').value.trim();
            var destination = document.getElementById('destination-input').value.trim();
            
            if (!origin || !destination) {
                alert('请输入起点和终点');
                return;
            }
            
            document.getElementById('status').innerHTML = "正在查询路线...";
            
            // 清除之前的结果
            document.getElementById('routes-table').style.display = 'none';
            document.getElementById('route-details').style.display = 'none';
            
            // 调用API获取路线数据
            callNavigationApi(origin, destination);
        }
        
        // 调用后端导航API
        function callNavigationApi(origin, destination) {
            console.log("调用导航API, 起点:", origin, "终点:", destination);
            document.getElementById('status').innerHTML = "正在获取路线数据...";
            
            var apiUrl = `/api/navigation/driving?origin=${encodeURIComponent(origin)}&destination=${encodeURIComponent(destination)}&alternatives=true`;
            console.log("API URL:", apiUrl);
            
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("API返回数据:", data);
                    if (data.status !== 0) {
                        document.getElementById('status').innerHTML = "获取路线失败: " + data.message;
                        alert('获取路线失败: ' + data.message);
                        return;
                    }
                    
                    // 处理路线数据
                    processRouteData(data);
                })
                .catch(error => {
                    console.error('获取路线出错:', error);
                    document.getElementById('status').innerHTML = "获取路线出错: " + error.message;
                    alert('获取路线时发生错误: ' + error.message);
                });
        }
        
        // 处理路线数据
        function processRouteData(data) {
            if (!data.result || !data.result.routes || data.result.routes.length === 0) {
                document.getElementById('status').innerHTML = "未找到路线";
                return;
            }
            
            // 保存路线数据
            routeResults = data.result.routes;
            
            // 显示路线表格
            displayRoutesTable(routeResults);
            
            // 显示第一条路线详情
            showRouteDetails(0);
            
            document.getElementById('status').innerHTML = "找到 " + routeResults.length + " 条路线";
        }
        
        // 显示路线表格
        function displayRoutesTable(routes) {
            var tbody = document.getElementById('routes-tbody');
            tbody.innerHTML = '';
            
            routes.forEach(function(route, index) {
                var tr = document.createElement('tr');
                tr.setAttribute('data-index', index);
                
                // 设置选中状态
                if (index === 0) {
                    tr.className = 'selected';
                    currentRouteIndex = 0;
                }
                
                // 设置标签样式类
                var tagClass = '';
                if (route.tag === '推荐路线') {
                    tagClass = 'recommended';
                } else if (route.tag === '备选路线1') {
                    tagClass = 'alternative1';
                } else if (route.tag === '备选路线2') {
                    tagClass = 'alternative2';
                }
                
                // 格式化距离和时间
                var distance = (route.distance / 1000).toFixed(1);
                var duration = formatDuration(route.duration);
                var toll = route.toll ? (route.toll / 100).toFixed(2) + ' 元' : '免费';
                
                tr.innerHTML = `
                    <td><span class="tag ${tagClass}">${route.tag || '路线' + (index + 1)}</span></td>
                    <td>${distance}</td>
                    <td>${duration}</td>
                    <td>${route.traffic_light || 0} 个</td>
                    <td>${route.traffic_condition || '未知'}</td>
                    <td>${toll}</td>
                    <td><button class="button" onclick="showRouteDetails(${index})">查看详情</button></td>
                `;
                
                tbody.appendChild(tr);
            });
            
            // 显示表格
            document.getElementById('routes-table').style.display = 'table';
        }
        
        // 显示路线详情
        function showRouteDetails(index) {
            if (index < 0 || index >= routeResults.length) {
                return;
            }
            
            currentRouteIndex = index;
            var route = routeResults[index];
            
            // 更新表格选中状态
            var rows = document.getElementById('routes-tbody').getElementsByTagName('tr');
            for (var i = 0; i < rows.length; i++) {
                rows[i].className = i === index ? 'selected' : '';
            }
            
            // 显示路线概要信息
            var summaryDiv = document.getElementById('route-summary');
            var distance = (route.distance / 1000).toFixed(1) + ' 公里';
            var duration = formatDuration(route.duration);
            var toll = route.toll ? (route.toll / 100).toFixed(2) + ' 元' : '免费';
            
            summaryDiv.innerHTML = `
                <p><strong>路线标签:</strong> ${route.tag || '路线' + (index + 1)}</p>
                <p><strong>总距离:</strong> ${distance} | <strong>预计耗时:</strong> ${duration} | <strong>红绿灯:</strong> ${route.traffic_light || 0}个 | <strong>过路费:</strong> ${toll}</p>
            `;
            
            // 显示步骤详情
            var stepsTable = document.getElementById('steps-tbody');
            stepsTable.innerHTML = '';
            
            if (route.steps && route.steps.length > 0) {
                route.steps.forEach(function(step, stepIndex) {
                    var tr = document.createElement('tr');
                    
                    var stepDistance = (step.distance / 1000).toFixed(1) + ' 公里';
                    var stepDuration = formatDuration(step.duration);
                    var trafficCondition = '';
                    
                    // 处理路况信息，可能是数组或字符串
                    if (step.traffic_condition) {
                        if (typeof step.traffic_condition === 'string') {
                            trafficCondition = step.traffic_condition;
                        } else if (Array.isArray(step.traffic_condition)) {
                            trafficCondition = step.traffic_condition.map(tc => {
                                let status = '';
                                switch(tc.status) {
                                    case 0: status = '畅通'; break;
                                    case 1: status = '缓行'; break;
                                    case 2: status = '拥堵'; break;
                                    case 3: status = '严重拥堵'; break;
                                    default: status = '未知';
                                }
                                return `${status} (${(tc.distance || 0).toFixed(1)}米)`;
                            }).join(', ');
                        } else if (typeof step.traffic_condition === 'object') {
                            let tc = step.traffic_condition;
                            let status = '';
                            switch(tc.status) {
                                case 0: status = '畅通'; break;
                                case 1: status = '缓行'; break;
                                case 2: status = '拥堵'; break;
                                case 3: status = '严重拥堵'; break;
                                default: status = '未知';
                            }
                            trafficCondition = `${status} (${(tc.distance || 0).toFixed(1)}米)`;
                        }
                    }
                    
                    // 生成导航指示
                    var instruction = '';
                    if (stepIndex === 0) {
                        instruction = '从起点出发，沿' + (step.road_name || '无名路') + '行驶';
                    } else if (stepIndex === route.steps.length - 1) {
                        instruction = '沿' + (step.road_name || '无名路') + '行驶到达终点';
                    } else {
                        // 根据方向生成指示
                        var directionText = '';
                        switch(step.direction) {
                            case 0: directionText = '直行'; break;
                            case 1: directionText = '左转'; break;
                            case 2: directionText = '右转'; break;
                            case 3: directionText = '向东'; break;
                            case 4: directionText = '向南'; break;
                            case 5: directionText = '向西'; break;
                            case 6: directionText = '向北'; break;
                            default: directionText = '继续前行';
                        }
                        instruction = directionText + '，沿' + (step.road_name || '无名路') + '行驶';
                    }
                    
                    tr.innerHTML = `
                        <td>${stepIndex + 1}</td>
                        <td>${step.road_name || '无名路'}</td>
                        <td>${instruction}</td>
                        <td>${stepDistance}</td>
                        <td>${stepDuration}</td>
                        <td>${trafficCondition}</td>
                    `;
                    
                    stepsTable.appendChild(tr);
                });
            } else {
                stepsTable.innerHTML = '<tr><td colspan="6">无详细步骤信息</td></tr>';
            }
            
            // 显示详情区域
            document.getElementById('route-details').style.display = 'block';
            
            // 滚动到详情区域
            document.getElementById('route-details').scrollIntoView({ behavior: 'smooth' });
        }
        
        // 格式化时间
        function formatDuration(seconds) {
            if (!seconds) return '未知';
            
            var hours = Math.floor(seconds / 3600);
            var minutes = Math.floor((seconds % 3600) / 60);
            
            if (hours > 0) {
                return hours + '小时' + minutes + '分钟';
            } else {
                return minutes + '分钟';
            }
        }
        
        // 点击页面其他地方关闭搜索结果
        document.addEventListener('click', function(e) {
            var originResults = document.getElementById('origin-search-results');
            var destResults = document.getElementById('destination-search-results');
            var originSearch = document.getElementById('origin-search');
            var destSearch = document.getElementById('destination-search');
            
            if (e.target !== originSearch && e.target !== originResults) {
                originResults.style.display = 'none';
            }
            
            if (e.target !== destSearch && e.target !== destResults) {
                destResults.style.display = 'none';
            }
        });
    </script>
</body>
</html> 